import 'package:flutter_yishop/config/Config.dart';
import 'package:flutter_yishop/constants/Constants.dart';
import 'package:sp_util/sp_util.dart';

class CartServices {
  static final String id = '_id';
  static final String title = 'title';
  static final String price = 'price';
  static final String selectedAttr = 'selectedAttr';
  static final String count = 'count';
  static final String pic = 'pic';
  static final String checked = 'checked';

  static addCart(item) {
    //把对象转换为map
    item = CartServices.formatCartData(item);

    /**
     *
        1、获取本地存储的cartList数据
        2、判断cartList是否有数据
        有数据：
        1、判断购物车有没有当前数据：
        有当前数据：
        1、让购物车中的当前数据数量 等于以前的数量+现在的数量
        2、重新写入本地存储

        没有当前数据：
        1、把购物车cartList的数据和当前数据拼接，拼接后重新写入本地存储。

        没有数据：
        1、把当前商品数据以及属性数据放在数组中然后写入本地存储



        List list=[
        {"_id": "1",
        "title": "磨砂牛皮男休闲鞋-有属性",
        "price": 688,
        "selectedAttr": "牛皮 ,系带,黄色",
        "count": 4,
        "pic":"public\upload\RinsvExKu7Ed-ocs_7W1DxYO.png",
        "checked": true
        },
        {"_id": "2",
        "title": "磨xxxxxxxxxxxxx",
        "price": 688,
        "selectedAttr": "牛皮 ,系带,黄色",
        "count": 2,
        "pic":"public\upload\RinsvExKu7Ed-ocs_7W1DxYO.png",
        "checked": true
        }

        ];

     */
    try {
      List cartListData = SpUtil.getObjectList(Constants.CARTLIST);
      //判断购物车有没有当前数据
      bool hasData = cartListData.any((value) {
        return value[id] == item[id] &&
            value[selectedAttr] == item[selectedAttr];
      });
      if (hasData) {
        for (int i = 0; i < cartListData.length; i++) {
          if (cartListData[i][id] == item[id] &&
              cartListData[i][selectedAttr] == item[i][selectedAttr]) {
            cartListData[i][count] = cartListData[i][count] + 1;
          }
        }
        SpUtil.putObjectList(Constants.CARTLIST, cartListData);
      } else {
        cartListData.add(item);
        SpUtil.putObjectList(Constants.CARTLIST, cartListData);
      }
    } catch (e) {
      List tempList = new List();
      tempList.add(item);
      SpUtil.putObjectList(Constants.CARTLIST, tempList);
    }
  }

  //过滤数据
  static formatCartData(item) {
    final Map data = Map();
    data[id] = item.sId;
    data[title] = item.title;
    data[price] = item.price;
    data[selectedAttr] = item.selectedAttr;
    data[count] = item.count;
    data[pic] = "${Config.url}${(item.pic).replaceAll("\\", "/")}";
    //是否选中
    data[checked] = true;
    return data;
  }

  //获取购物车选中数据
  static List getCheckOutData(){
    List cartListData = [];
    List tempCheckOutData = [];
    try{
      cartListData = SpUtil.getObjectList(Constants.CARTLIST);
    }catch(e){
      cartListData=[];
    }
    for(int i = 0;i<cartListData.length;i++){
      if(cartListData[i][CartServices.checked]==true){
        tempCheckOutData.add(cartListData[i]);
      }
    }
    return tempCheckOutData;
  }


}
